package cn.idu.rmi;

import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class RmiTest {

    private static final String REMOTE_P1 = "rmi-service:p1";
    private static final int port = 9900;

    public static void main(String[] args) throws RemoteException {
        //1. 定义远程服务接口, 实现接口方法
        //2. 实例化远程对象，并创建远程代理类
        RemoteService p1 = new pServices();
        Remote stub1 = UnicastRemoteObject.exportObject(p1, 0);
        //3. 启动服务
        //  1. 通过程序启动
        Registry registry = LocateRegistry.createRegistry(port);
        //  2. 通过命令启动：/usr/bin/rmiregistry port

        //4. 注册远程代理类
        registry.rebind(REMOTE_P1, stub1);
        System.out.println("service b bind!");


        //TODO 调用远程服务

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    //1. 连接仓库
                    Registry registry = LocateRegistry.getRegistry(port);

                    //2. 在Registry仓库中查找所调用服务的远程代理类
                    RemoteService p1 = (RemoteService) registry.lookup(REMOTE_P1);

                    //3. 调用代理类方法
                    String ret = (String) p1.run();
                    System.out.println("client invoke p1 run! - " + ret);

                    String ret1 = (String) p1.run("params0");
                    System.out.println("client invoke p1 run! - " + ret1);


                } catch (RemoteException | NotBoundException e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }
}
